import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:agent_process_app/utils/myUtils.dart' as myUtils;
import 'package:shared_preferences/shared_preferences.dart';

//const ListTile({
//Key key,
//this.leading,              // item 前置图标
//this.title,                // item 标题
//this.subtitle,             // item 副标题
//this.trailing,             // item 后置图标
//this.isThreeLine = false,  // item 是否三行显示
//this.dense,                // item 直观感受是整体大小
//this.contentPadding,       // item 内容内边距
//this.enabled = true,
//this.onTap,                // item onTap 点击事件
//this.onLongPress,          // item onLongPress 长按事件
//this.selected = false,     // item 是否选中状态
//})

class ChangePwdScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ChangePwd();
  }
}

class ChangePwd extends State<ChangePwdScreen> {
  final _oldPasswordController = TextEditingController();
  final _newPasswordController = TextEditingController();
  final _checkPasswordController = TextEditingController();

  Widget commitStatus = Icon(Icons.check_circle_outline,);

  changePwd(BuildContext context) async {
    String oldPwd = _oldPasswordController.text;
    String newPwd = _newPasswordController.text;
    String checkPwd = _checkPasswordController.text;

    //判断不能为空
    if (oldPwd.isEmpty ||
        newPwd.isEmpty ||
        checkPwd.isEmpty ||
        oldPwd.length < 6 ||
        oldPwd.length > 18 ||
        newPwd.length < 6 ||
        newPwd.length > 18 ||
        checkPwd.length < 6 ||
        checkPwd.length > 18) {
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("密码格式不正确!"),
                  content: Text("长度必须大于6位但不能超过18位!"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )
                  ]));
      return;
    }
    //判断新密码和确认密码是否一致
    if (newPwd != checkPwd) {
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("确认密码与新密码不一致!"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )
                  ]));
      return;
    }
    //判断旧密码与新密码是否一致
    if (oldPwd == newPwd) {
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("新密码与旧密码一致,无须修改!"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )
                  ]));
      return;
    }
    //发送请求,base64加密
    setState(() {
      //改变状态
      commitStatus = CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation(Colors.white),
        strokeWidth: 2.0,
      );
    });
    String token;
    await myUtils.LocalStorage.getLocalStorageInstance()
        .then((SharedPreferences sharedPreferences) {
      token = sharedPreferences.getString("token");
    });

    FormData formData = new FormData.from({
      "oldPwd": base64Encode(utf8.encode(oldPwd)),
      "newPwd": base64Encode(utf8.encode(newPwd)),
    });

    Dio dio = myUtils.MyDio.getDio(token);
    Response response = await dio.post("/updatePwd", data: formData);

    setState(() {
      //改变状态
      commitStatus = Icon(Icons.check_circle_outline);
    });

    int resCode = response.data["Code"];
    print(resCode);
    //2019年2月10日 14:37:03 写到这里,写处理的逻辑
    if (resCode == 200) {
      //密码修改成功
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("安全提醒"),
                  content: new Text("密码修改成功，请重新登录！"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();

                        SharedPreferences.getInstance().then((s) {
                          myUtils.MyUtils.clearUserInfo();
                          Navigator.of(context).pushNamedAndRemoveUntil(
                              "/loginScreen", (route) => route == null);
                        });
                      },
                    )
                  ]));
    } else if (resCode == 403) {
      //无权限
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("安全提醒"),
                  content: new Text("由于登录已过期，本次密码修改失败，请重新登录后重试！"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();

                        SharedPreferences.getInstance().then((s) {
                          myUtils.MyUtils.clearUserInfo();
                          Navigator.of(context).pushNamedAndRemoveUntil(
                              "/loginScreen", (route) => route == null);
                        });
                      },
                    )
                  ]));
    } else if (resCode == 405) {
      //密码错误
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("安全提醒"),
                  content: new Text("旧密码错误！"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )
                  ]));
    } else if (resCode == 500) {
      //服务器异常
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("安全提醒"),
                  content: new Text("抱歉，服务器未知异常！"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    )
                  ]));
    }
  }

  //后面的叉号
  Widget oldPwdSuffixButton;
  Widget newPwdSuffixButton;
  Widget checkPwdSuffixButton;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("修改密码"),
        actions: <Widget>[
          IconButton(
            icon: commitStatus,
            tooltip: "提交",
            onPressed: () {
              changePwd(
                context,
              );
            },
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Center(
            child: Container(
          padding: const EdgeInsets.only(left: 10.0, right: 10.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextField(
                onChanged: (value) {
                  setState(() {
                    if (value.isNotEmpty) {
                      oldPwdSuffixButton = IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            _oldPasswordController.clear();
                          });
                    } else {
                      oldPwdSuffixButton = null;
                    }
                  });
                },
                obscureText: true,
                controller: _oldPasswordController,
                decoration: InputDecoration(
                  icon: Icon(Icons.lock_open),
                  labelText: "旧密码",
                  suffixIcon: oldPwdSuffixButton, //输入框内右侧图标
                ),
              ),
              TextField(
                onChanged: (value) {
                  setState(() {
                    if (value.isNotEmpty) {
                      newPwdSuffixButton = IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            _newPasswordController.clear();
                          });
                    } else {
                      newPwdSuffixButton = null;
                    }
                  });
                },
                controller: _newPasswordController,
                obscureText: true,
                //让输入的内容变成圆点,输入密码场景中适用
                decoration: InputDecoration(
                  icon: Icon(Icons.lock_outline),
                  labelText: "新密码",
                  suffixIcon: newPwdSuffixButton, //输入框内右侧图标
                ),
              ),
              TextField(
                onChanged: (value) {
                  setState(() {
                    if (value.isNotEmpty) {
                      checkPwdSuffixButton = IconButton(
                          icon: Icon(Icons.clear),
                          onPressed: () {
                            _checkPasswordController.clear();
                          });
                    } else {
                      checkPwdSuffixButton = null;
                    }
                  });
                },
                onSubmitted: (text) {
                  changePwd(
                    context,
                  );
                },
                controller: _checkPasswordController,
                obscureText: true,
                //让输入的内容变成圆点,输入密码场景中适用
                decoration: InputDecoration(
                  icon: Icon(Icons.lock_outline),
                  labelText: "确认新密码",
                  suffixIcon: checkPwdSuffixButton, //输入框内右侧图标
                ),
              ),
            ],
          ),
        )),
      ),
    );
  }
}
